package com.gexin.controller.xapp.product;

import com.gexin.common.AppGlobal;
import com.gexin.common.kusy.KusyUtil;
import com.gexin.common.utils.RedisLockTool;
import com.gexin.common.utils.StringUtil;
import com.gexin.model.agent.Agent;
import com.gexin.model.order.Order;
import com.gexin.model.order.OrderItem;
import com.gexin.model.order.OrderPresale;
import com.gexin.model.system.AddrCities;
import com.gexin.model.weixin.UserAddress;
import com.gexin.model.weixin.WeixinUser;
import com.gexin.service.agent.AgentService;
import com.gexin.service.memberAcitivty.IntegralService;
import com.gexin.weixin.kit.WeiXinUtils;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.HttpKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.kit.PaymentKit;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 微信APP支付成功回调
 *
 * @author 肖得明
 */
@ControllerBind(controllerKey = "/xapp/order/pay/notify")
public class OrderAppPayNotifyController extends Controller {
    static final Log log = Log.getLog(OrderAppPayNotifyController.class);

    @Before(Tx.class)
    public boolean index() {
        String lock_key = "cache:order:lock:";
        try {
            String xmlMsg = HttpKit.readData(getRequest());
            if(StringUtil.isBlank(xmlMsg)){
                return false;
            }
            log.info("订单付款APP微信支付成功回调=====" + xmlMsg);
            Map<String, String> map = PaymentKit.xmlToMap(xmlMsg);
            if (map != null && map.get("result_code").toString().trim().equals("SUCCESS")) {
                // 如果验证码成功 要判断订单别重复提交了
                String out_trade_no = map.get("out_trade_no");// 支付订单ID
                String transaction_id = map.get("transaction_id");//微信的流水ID
                Integer total_fee = Integer.parseInt(map.get("total_fee"));// 支付多少钱
                log.info(String.format("订单APP支付成功通知，内部ID:%s,微信支付ID:%s,支付金额：%s分", out_trade_no, transaction_id, total_fee));

                lock_key = lock_key + out_trade_no;
                boolean lock_get_state = RedisLockTool.getLock(lock_key, 5000);  //获取锁
                if (lock_get_state) {
                    Order order = Order.dao.findById(out_trade_no);
                    if (order == null) {
                        log.error("app支付回调发生异常错误:  订单不存在" + out_trade_no + "   transaction_id:" + transaction_id);
                        renderXml(WeiXinUtils.wxPayResponse("FAIL", ""));
                        return false;
                    }
                    if (order.getPayState() != 0 && !order.getState().equals(order.State_Wait_Pay)) {
                        log.error("APP订单已经被支付处理过了 " + out_trade_no + "   transaction_id:" + transaction_id);
                        renderXml(WeiXinUtils.wxPayResponse("FAIL", ""));
                        return false;
                    }
                    Order order_new = new Order();
                    order_new.setId(order.getId());
                    order_new.setPayTime(new Date());
                    order_new.setPayState(2);
                    order_new.setPayType(4);
                    order_new.setTransactionId(transaction_id);
                    order_new.setState(order.State_Wait_Send_Express);
                    order_new.setTotalFee(total_fee);


                    if (order.getType() == 2) {
                        OrderPresale presale = OrderPresale.dao.findByOrderIdAndType(order.getId(), 1);
                        if (presale != null) {
                            if (presale.getState() == 1) {
                                order_new.setPayState(1);
                                presale.setState(2);
                                presale.setTransactionId(transaction_id);
                                presale.setPayMoney(new BigDecimal(total_fee / 100 + ""));
                                presale.setPayTime(new Date());
                                presale.update();
                            } else {
                                log.error("商品APP支付回调方法，order_id：" + order_new.getId() + "，在 OrderPresale 表中 订金状态显示已支付 ！ ");
                                renderXml(WeiXinUtils.wxPayResponse("FAIL", ""));
                                return false;
                            }
                        } else {
                            log.error("商品APP支付回调方法，order_id：" + order_new.getId() + "，在 OrderPresale 表未找到数据 ！ ");
                            renderXml(WeiXinUtils.wxPayResponse("FAIL", ""));
                            return false;
                        }
                    }


                    if (order_new.update()) {
                        IntegralService inviterService = new IntegralService();
                        inviterService.confirmDelivery(order, order.getUserId() + "");
                        agentServ(order_new);
                        //处理成功
                        renderText("success");

                     } else {
                        log.error("订单修改保存失败! " + out_trade_no + "   transaction_id:" + transaction_id);
                        renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
                    }
                } else {
                    renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
                }
            } else {
                renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
            }
        } catch (Exception e) {
            log.error("支付回调发生异常错误:", e.fillInStackTrace());
            renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
        } finally {
            RedisLockTool.releaseLock(lock_key);//释放锁
        }
        return false;
    }


//	public void gee(){
//		//			购买完成时给redis添加状态
//		LocalDateTime localDateTime = LocalDateTime.now();
//		String format = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//		String key = order.getUserId()+"_"+format;
//		String id = order_new.getId();
//		List<OrderItem> orderItemList = OrderItem.dao.getOrderItemsByOrderId(id);
//
//		Page<FreeAcquire> freeAcquirePage = freeAcquireService.findList(1, 10);
//		List<FreeAcquire> freeAcquireList = freeAcquirePage.getList();
//		Jedis jedis = Redis.use().getJedis();
//	//			for(int i=0;i<freeAcquireList.size();i++){
//	//				FreeAcquire freeAcquire = freeAcquireList.get(i);
//	//				for(int j=0;j<orderItemList.size();j++){
//	//					OrderItem orderItem = orderItemList.get(j);
//	//					String orderItemProductId = orderItem.getProductId() + "";
//	//					if(StringUtils.isNotBlank(orderItemProductId) &&
//	//							StringUtils.isNotBlank(freeAcquire.getProductId()) &&
//	//							orderItemProductId.equals(freeAcquire.getProductId())){
//	//							jedis.set(key,orderItemProductId);
//	//					}
//	//				}
//	//			}
//
//		freeAcquireList.stream().
//				forEach(freeAcquire -> {
//					orderItemList.stream().
//							forEach(orderItem -> {
//								String orderItemProductId = orderItem.getProductId() + "";
//								if(StringUtils.isNotBlank(orderItemProductId) &&
//										StringUtils.isNotBlank(freeAcquire.getProductId()) &&
//										orderItemProductId.equals(freeAcquire.getProductId())){
//									jedis.set(key,orderItemProductId);
//								}
//							});
//				});
//		jedis.close();
//
//	}

    //小程序回调
    @Before(Tx.class)
    public void xapp() {
        String lock_key = "cache:order:lock:";
		try {

        log.info("微信支付成功回调=====");
        SortedMap<String, String> params = new TreeMap<>();
        Enumeration<String> paraNames = getParaNames();
        for (Enumeration<String> e = paraNames; e.hasMoreElements(); ) {
            String thisName = e.nextElement().toString();
            String thisValue = getPara(thisName);
            if (AppGlobal.dev_Mode) {
                System.err.println("param的key:" + thisName + "--------------param的value:" + thisValue);
            }
            params.put(thisName, thisValue);
        }
        String sign = KusyUtil.createSign(params, KusyUtil.Sign_Key);


        if (sign.equals(getPara("sign"))) {
			String out_trade_no = getPara("mch_orderid");
			String transaction_id = getPara("orderid");//支付系统id
			BigDecimal pay_money = new BigDecimal(getPara("pri_paymoney"));//支付金额


			lock_key = lock_key + out_trade_no;
			boolean lock_get_state = RedisLockTool.getLock(lock_key, 5000);  //获取锁
			if (lock_get_state) {
				Order order = Order.dao.findById(out_trade_no);
				if (order == null) {
					log.error("支付回调发生异常错误:  订单不存在" + out_trade_no + "   transaction_id:" + transaction_id);
					renderText("fail");
					return;
				}
				if (order.getPayState() !=0 && !order.getState().equals(order.State_Wait_Pay)) {
                    log.error("订单已经被支付处理过了 " + out_trade_no + "   transaction_id:" + transaction_id);
                    renderText("fail");
                    return;
                }

				Order order_new = new Order();
				order_new.setId(order.getId());
				order_new.setPayTime(new Date());
                order_new.setPayState(2);
				order_new.setPayType(5);
//                order_new.setState(1);
                order_new.setState(order.State_Wait_Send_Express);
                order_new.setTotalFee(pay_money.intValue() * 100);


				if (order.getType() == 2) {
					OrderPresale presale = OrderPresale.dao.findByOrderIdAndType(order.getId(), 1);
					if (presale != null) {
						if (presale.getState() == 1) {
							order_new.setPayState(1);
							presale.setState(2);
							presale.setTransactionId(transaction_id);
							presale.setPayMoney(pay_money);
							presale.setPayTime(new Date());
							presale.update();
						} else {
							log.error("商品支付回调方法，order_id：" + order_new.getId() + "，在 OrderPresale 表中 订金状态显示已支付 ！ ");
							renderText("fail");
							return;
						}
					} else {
						log.error("商品支付回调方法，order_id：" + order_new.getId() + "，在 OrderPresale 表未找到数据 ！ ");
						renderText("fail");
						return;
					}
				}

                boolean update = order_new.update();
                if (update) {
					agentServ(order_new);
					IntegralService inviterService = new IntegralService();
					inviterService.confirmDelivery(order, order.getUserId() + "");
					//处理成功
                    renderText(WeiXinUtils.wxPayResponse("SUCCESS", "OK"));
//				renderText("success");
					return;
				} else {
					log.error("订单修改保存失败! " + out_trade_no + "   transaction_id:" + transaction_id);
					renderText("fail");
				}

			} else {
				log.error("支付回调验签错误");
				renderText("fail");
			}
		}
		}catch(Exception ex) {
			log.error("支付回调发生异常错误:", ex.fillInStackTrace());
			renderText(WeiXinUtils.wxPayResponse("FAIL", ""));

		}finally {
			RedisLockTool.releaseLock(lock_key);//释放锁
		}
            return;
        }



        private void agentServ (Order order_new){
            Order oldOrder = (Order) Order.dao.findById(order_new.getId());
            if ((oldOrder.getRegisterOrder() != null) && (oldOrder.getRegisterOrder().intValue() == 1)) {
                Integer userId = oldOrder.getUserId();
                WeixinUser weixinUser = (WeixinUser) WeixinUser.dao.findById(userId);
                Agent agent = Agent.dao.findInfoByUserIdALL(userId);
                if (agent != null) {
                    agent.setControlMoneyAmount(order_new.getTotalAmount());
                    agent.setControlMoenyState(Agent.PAY_TYPE_YIZHIFU);
                    agent.update();
                }
            } else {
                Order sendOrder = (Order) Order.dao.findById(order_new.getId());
                String payTimeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(sendOrder.getCreatetime());

                Integer userId = sendOrder.getUserId();
                WeixinUser payUser = (WeixinUser) WeixinUser.dao.findById(userId);
                Integer agentId = sendOrder.getAgentId();
                Agent agent = (Agent) Agent.dao.findById(agentId);
                BigDecimal pi = new BigDecimal(0.0D);
                if (agent != null) {
                    Map<String, BigDecimal> stringBigDecimalMap = new HashMap();
                    WeixinUser agentUser = (WeixinUser) WeixinUser.dao.findById(agent.getUserId());
                    List<OrderItem> item = OrderItem.dao.findOrderItemByOrderId(sendOrder.getId());
                    if (sendOrder.getAgentId() != null) {
                        UserAddress address = (UserAddress) UserAddress.dao.findById(sendOrder.getAddressId());

                        stringBigDecimalMap = AgentService.dao.calcDiGui(agent, item, null, new BigDecimal(0.0D), sendOrder, null, null, BigDecimal.ZERO);
                    }
                    if ((agentUser != null) && (stringBigDecimalMap.get("profits") != null) && (agentUser.getOpenid() != null)) {
                        AgentService.dao.sendSaveTemplateMsg(sendOrder.getId(), sendOrder.getExpressReceiveName(), sendOrder.getTotalAmount().toString(), payTimeStr, sendOrder
                                .getExpressPhone(), agentUser.getOpenid(), (BigDecimal) stringBigDecimalMap.get("profits"));
                        pi = (BigDecimal) stringBigDecimalMap.get("profits");

                        Integer extensionId = agent.getParentId();
                        if (extensionId != null) {
                            Agent agent1 = (Agent) Agent.dao.findById(extensionId);
                            if (agent1 != null) {
                                Map<String, BigDecimal> stringBigDecimalMap1 = AgentService.dao.calcDiGui(agent1, item, agent.getId(), (BigDecimal) stringBigDecimalMap.get("agentDecimal"), sendOrder, Integer.valueOf(0), new BigDecimal(0.0D), (BigDecimal) stringBigDecimalMap.get("profits"));
                                WeixinUser weixinUser = (WeixinUser) WeixinUser.dao.findById(agent1.getUserId());
                                AgentService.dao.sendSaveTemplateMsg(sendOrder.getId(), sendOrder.getExpressReceiveName(), sendOrder.getTotalAmount().toString(), payTimeStr, sendOrder
                                        .getExpressPhone(), weixinUser.getOpenid(), (BigDecimal) stringBigDecimalMap1.get("profits"));
                                pi = (BigDecimal) stringBigDecimalMap1.get("profits");
                            }
                        }
                    }
                }
                BigDecimal bigDecimal = AgentService.dao.sendAreaAgentAddPrice(sendOrder, pi);
                if (bigDecimal == null) {
                    bigDecimal = BigDecimal.ZERO;
                }
                Integer addressId = sendOrder.getAddressId();
                UserAddress userAddress = (UserAddress) UserAddress.dao.findById(addressId);
                if (userAddress != null) {
                    AddrCities addrCities = AddrCities.dao.findByCityId(userAddress.getCityId().toString());
                    if (addrCities != null) {
                        Agent areaAgent = (Agent) Agent.dao.findById(addrCities.getAgentId());
                        if (areaAgent != null) {
                            WeixinUser weixinUser = (WeixinUser) WeixinUser.dao.findById(areaAgent.getUserId());
                            if ((weixinUser != null) && (bigDecimal.compareTo(BigDecimal.ZERO) != 0)) {
                                AgentService.dao.sendSaveTemplateMsg(sendOrder.getId(), sendOrder.getExpressReceiveName(), sendOrder.getTotalAmount().toString(), payTimeStr, sendOrder
                                        .getExpressPhone(), weixinUser.getOpenid(), bigDecimal);
                            }
                        }
                    }
                }
            }
        }


        /**
         * =========================================尾款=========================================
         */

        //APP微信支付回调
        @Before(Tx.class)
        public void tail_app () {
            String lock_key = "cache:tail:product:lock:";
            try {
                String xmlMsg = HttpKit.readData(getRequest());
                log.info("预售商品 尾款 微信支付成功回调=====" + xmlMsg);
                Map<String, String> map = PaymentKit.xmlToMap(xmlMsg);
                if (map != null && map.get("result_code").toString().trim().equals("SUCCESS")) {
                    // 如果验证码成功 要判断订单别重复提交了
                    String out_trade_no = map.get("out_trade_no");// 支付订单ID
                    String transaction_id = map.get("transaction_id");//微信的流水ID
                    Integer total_fee = Integer.parseInt(map.get("total_fee"));// 支付多少钱
                    log.info(String.format("预售商品 尾款 订单支付成功通知，内部ID:%s,微信支付ID:%s,支付金额：%s分", out_trade_no, transaction_id, total_fee));
                    lock_key = lock_key + out_trade_no;
                    boolean lock_get_state = RedisLockTool.getLock(lock_key, 5000);  //获取锁
                    if (lock_get_state) {
                        //这里注释下  尾款传入过来的订单号 后面带了 t_order_presale 主键ID
                        out_trade_no = out_trade_no.split("_")[0];
                        Order order = Order.dao.findById(out_trade_no);
                        if (order == null) {
                            log.error("支付回调发生异常错误:  订单不存在" + out_trade_no + "   transaction_id:" + transaction_id);
                            renderXml(WeiXinUtils.wxPayResponse("FAIL", ""));
                            return;
                        }
                        if (order.getPayState() != 1 && !order.getState().equals(order.State_Wait_Send_Express)) {
                            log.error("订单已经被支付处理过了 " + out_trade_no + "   transaction_id:" + transaction_id);
                            renderXml(WeiXinUtils.wxPayResponse("FAIL", ""));
                            return;
                        }
                        Order order_new = new Order();
                        order_new.setId(order.getId());
                        order_new.setPayTime(new Date());
                        order_new.setPayState(2);
                        order_new.setPayType(4);
                        order_new.setTransactionId(transaction_id);
                        order_new.setState(order.State_Wait_Send_Express);
                        order_new.setTotalFee(total_fee);
                        Integer userId = order_new.getUserId();
//					if(userId!=null){
//						String id = order_new.getId();
//						List<OrderItem> orderItemByOrderId = OrderItem.dao.findOrderItemByOrderId(id);
//						List<MemberProductIntegral> memberProductIntegralList =  MemberProductIntegral.dao.findAll();
//
//						for(int i=0;i<orderItemByOrderId.size();i++) {
//							OrderItem orderItem = orderItemByOrderId.get(i);
//							Integer productId = orderItem.getProductId();
//							List<MemberProductIntegral> collect = memberProductIntegralList.stream().filter(memberProductIntegral -> memberProductIntegral.getProductId()
//									!= null && memberProductIntegral.getProductId().equals(productId)).collect(Collectors.toList());
//							if(collect.size()==0){
//								break;
//							}
//							MemberProductIntegral memberProductIntegral = collect.get(0);
//							Integer integral1 = memberProductIntegral.getIntegral()==null?0:memberProductIntegral.getIntegral();
//
//							MemberOrderIntegral memberOrderIntegral = new MemberOrderIntegral();
//							memberOrderIntegral.setId(UUIDUtils.getUUIDInOrderId()+"");
//							Long date = new Date().getTime();
//							memberOrderIntegral.setCreateTime(date);
//							memberOrderIntegral.setUpdateTime(date);
//							memberOrderIntegral.setOrderItemId(orderItem.getItemId()+"");
//							memberOrderIntegral.setUserId(userId+"");
//							memberOrderIntegral.setBill(integral1);
//							memberOrderIntegral.setStatus(1);
//
//							MemberIntegralLog memberIntegralLog = new MemberIntegralLog();
//							memberIntegralLog.setUserIdAndintegralAndIncrementIntegralAndStatusAndCommissionAndReserveAndDesc(
//									2,userId+"",integral1,0,true,0,0,"买东西赠送积分"
//							);
//							memberIntegralLog.save();
//						}
//					}

                        //修改状态
                        OrderPresale presale = OrderPresale.dao.findByOrderIdAndType(order.getId(), 2);
                        if (presale == null) {
                            log.error("订单： " + out_trade_no + "   transaction_id:" + transaction_id + "，OrderPresale 没有找到数据！");
                            renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
                        }
                        presale.setTransactionId(transaction_id);
                        presale.setState(2);
                        presale.setPayTime(new Date());
                        presale.setPayMoney(new BigDecimal(total_fee + "").divide(new BigDecimal("100")));
                        presale.update();


                        if (order_new.update()) {
                            IntegralService inviterService = new IntegralService();
                            inviterService.confirmDelivery(order, order.getUserId() + "");
                            //处理成功
                            renderText(WeiXinUtils.wxPayResponse("SUCCESS", ""));
                        } else {
                            log.error("订单修改保存失败! " + out_trade_no + "   transaction_id:" + transaction_id);
                            renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
                        }
                    } else {
                        renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
                    }
                } else {
                    renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
                }
            } catch (Exception e) {
                log.error("支付回调发生异常错误:", e.fillInStackTrace());
                renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
            } finally {
                RedisLockTool.releaseLock(lock_key);//释放锁
            }
        }
        //小程序微信支付回调
        public void tail_xapp () {
            log.info("微信支付成功回调=====");
            SortedMap<String, String> params = new TreeMap<>();
            Enumeration<String> paraNames = getParaNames();
            for (Enumeration<String> e = paraNames; e.hasMoreElements(); ) {
                String thisName = e.nextElement().toString();
                String thisValue = getPara(thisName);
                if (AppGlobal.dev_Mode) {
                    System.err.println("param的key:" + thisName + "--------------param的value:" + thisValue);
                }
                params.put(thisName, thisValue);
            }
            String sign = KusyUtil.createSign(params, KusyUtil.Sign_Key);
            if (sign.equals(getPara("sign"))) {
                String out_trade_no = getPara("mch_orderid");
                String transaction_id = getPara("orderid");//支付系统id
                BigDecimal pay_money = new BigDecimal(getPara("pri_paymoney"));//支付金额
                //这里注释下  尾款传入过来的订单号 后面带了 t_order_presale 主键ID
                out_trade_no = out_trade_no.split("_")[0];
                Order order = Order.dao.findById(out_trade_no);
                if (order == null) {
                    log.error("支付回调发生异常错误:  订单不存在" + out_trade_no + "   transaction_id:" + transaction_id);
                    renderText("fail");
                    return;
                }
                if (order.getPayState() != 1 && !order.getState().equals(order.State_Wait_Send_Express)) {
                    log.error("尾款订单已经被支付处理过了 " + out_trade_no + "   transaction_id:" + transaction_id);
                    renderText("fail");
                    return;
                }
                Order order_new = new Order();
                order_new.setId(order.getId());
                order_new.setPayTime(new Date());
                order_new.setPayState(2);
                order_new.setPayType(5);
                order_new.setTransactionId(transaction_id);
                order_new.setState(order.State_Wait_Send_Express);
                order_new.setTotalFee(pay_money.intValue() * 100);
                Integer userId = order_new.getUserId();


			IntegralService integralService = new IntegralService();
			integralService.confirmDelivery(order_new,order_new.getUserId()+"");
//              修改状态
                OrderPresale presale = OrderPresale.dao.findByOrderIdAndType(order.getId(), 2);
                if (presale == null) {
                    log.error("订单： " + out_trade_no + "   transaction_id:" + transaction_id + "，OrderPresale 没有找到数据！");
                    renderText("fail");
                }
                presale.setTransactionId(transaction_id);
                presale.setState(2);
                presale.setPayTime(new Date());
                presale.setPayMoney(pay_money);
                presale.update();
                if (order_new.update()) {
                    //处理成功
                    renderText("success");
                } else {
                    log.error("订单修改保存失败! " + out_trade_no + "   transaction_id:" + transaction_id);
                    renderText("fail");
                }
            } else {
                log.error("支付回调验签错误");
                renderText("fail");
            }

        }

    }
